<template>
  <el-menu-item index="video-monitor" @click="toggleVideoMonitor">
    <el-icon>
      <VideoCamera />
    </el-icon>
    <span>视频监控 {{ isActive ? '(激活中)' : '' }}</span>
  </el-menu-item>
  <div ref="popupEle" class="video-popup-container">
    <el-descriptions :column="1" border>
      <el-descriptions-item label="位置">
        {{ popupData.content.位置 || '暂无位置信息' }}
      </el-descriptions-item>
      <el-descriptions-item label="编号">
        {{ popupData.content.编号 || 'N/A' }}
      </el-descriptions-item>
      <el-descriptions-item label="视频">
        <div class="video-wrapper">
          <video v-if="videoSource" key="videoPlayer" ref="videoPlayer" class="video-container" controls
            preload="metadata" @loadeddata="handleVideoLoaded" @error="handleVideoError"></video>
          <div v-if="videoLoading" class="video-loading">
            <el-icon class="is-loading">
              <Loading />
            </el-icon>
            视频加载中...
          </div>
          <div v-if="videoError" class="video-error">
            <el-icon>
              <Warning />
            </el-icon>
            视频加载失败
          </div>
        </div>
      </el-descriptions-item>
      <template #extra>
        <el-button circle @click="closePopup">
          <el-icon>
            <Close />
          </el-icon>
        </el-button>
      </template>
    </el-descriptions>
  </div>
</template>

<script setup>
import { ref, watch, onUnmounted, nextTick } from 'vue'
import { useMapStore } from '@/stores/mapStore'
import { queryPointByPosition } from '@/api/mapgis-api/queryPointByPosition'
import { ElMessage } from 'element-plus'
import { VideoCamera, Loading, Warning, Close } from '@element-plus/icons-vue'

const mapStore = useMapStore()

// 响应式状态
const isActive = ref(false)
const popupEle = ref(null)
const videoPlayer = ref(null)
const videoSource = ref('')
const videoLoading = ref(false)
const videoError = ref(false)
const popupData = ref({ content: {} })

// 地图相关引用
let overlay = null
let mapClickListener = null


// 直接打开图层
const openLayer = () => {
  const targetLayer = mapStore.mapInstance.getLayers().getArray()[2]
  if (!targetLayer) {
    ElMessage.error('监控图层未找到')
    return
  }
  targetLayer.setLayerStatus([3], 'include')
}

// 视频控制
const handleVideoLoaded = () => {
  videoLoading.value = false
  try {
    videoPlayer.value.play()
  } catch (e) {
    console.log('自动播放被阻止:', e)
  }
}

const handleVideoError = () => {
  videoLoading.value = false
  videoError.value = true
  ElMessage.error('视频流加载失败')
}

// 弹窗管理
const updatePopupPosition = (coordinate) => {
  nextTick(() => {
    if (overlay) {
      overlay.setPosition(coordinate)
      // 自动调整弹窗位置避免超出视口
      const mapView = mapStore.mapInstance.getView()
      overlay.setPosition(mapView.constrainCenter(coordinate))
    }
  })
}

// 地图点击处理
// 修改后的地图点击处理函数
const handleMapClick = (e) => {
  if (!isActive.value) return

  videoLoading.value = true
  videoError.value = false

  // 保持原始插件的回调函数调用方式
  queryPointByPosition(
    e.coordinate,
    3,
    (data) => {
      try {
        if (data?.TotalCount > 0) {
          const format = new window.Zondy.Format.PolygonJSON()
          const features = format.read(data)
          const feature = features[0].values_.values_

          popupData.value = {
            content: {
              位置: feature.位置,
              编号: feature.编号,
              URL: feature.URL,
            },
          }

          videoSource.value = feature.URL || '/images/监控1.mp4'
          updatePopupPosition(e.coordinate)
        } else {
          ElMessage.warning('未找到监控点信息')
        }
      } catch (error) {
        console.error('数据解析失败:', error)
        ElMessage.error('数据格式错误')
      } finally {
        videoLoading.value = false
      }
    },
    (error) => {
      console.error('API调用失败:', error)
      ElMessage.error('获取监控信息失败')
      videoLoading.value = false
    }
  )
}

// 开启/关闭监控功能
const toggleVideoMonitor = () => {
  isActive.value = !isActive.value

  if (isActive.value) {
    openLayer() // 直接打开图层
    initMapListeners()
    ElMessage.success('视频监控已激活')
  } else {
    cleanup()
    ElMessage.info('视频监控已关闭')
  }
}

// 初始化地图监听
const initMapListeners = () => {
  // 清理旧监听
  if (mapClickListener) {
    mapStore.mapInstance.un('click', mapClickListener)
  }

  // 点击地图主体事件
  mapClickListener = mapStore.mapInstance.on('click', handleMapClick)
}

// 关闭弹窗
const closePopup = () => {
  if (overlay) overlay.setPosition(undefined)
  videoSource.value = ''
  popupData.value = { content: {} }

  // 重置视频状态
  if (videoPlayer.value) {
    videoPlayer.value.pause()
    videoPlayer.value.removeAttribute('src')
    videoPlayer.value.load()
  }
}

// 清理资源
const cleanup = () => {
  closePopup()
  if (mapClickListener) {
    window.ol.Observable.unByKey(mapClickListener)
  }
}

// 初始化地图覆盖物
watch(
  () => mapStore.mapInstance,
  (map) => {
    if (map && !overlay) {
      overlay = new window.ol.Overlay({
        element: popupEle.value,
        autoPan: true,
        autoPanMargin: 20,
        autoPanAnimation: {
          duration: 250,
          easing: window.ol.easing.easeOut,
        },
      })
      map.addOverlay(overlay)
    }
  },
  { immediate: true }
)

// 组件卸载清理
onUnmounted(() => {
  cleanup()
  if (overlay) {
    mapStore.mapInstance.removeOverlay(overlay)
    overlay = null
  }
})
</script>

<style lang="scss" scoped>
/* 保持原有样式不变 */
</style>

<style lang="scss" scoped>
.video-popup-container {
  position: absolute;
  pointer-events: auto;
  backdrop-filter: blur(3px);

  :deep(.el-descriptions) {
    background: rgba(16, 25, 40, 0.95);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 6px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
    color: white;
    max-width: 90vw;

    .el-descriptions__header {
      padding: 12px;
      background: rgba(255, 255, 255, 0.05);
    }

    .el-descriptions__label {
      color: #89b4fa;
      width: 80px;
      justify-content: flex-end;
    }

    .el-descriptions__content {
      padding: 8px 12px;
      min-width: 240px;
    }
  }
}

.video-wrapper {
  position: relative;
  background: #000;
  border-radius: 4px;
  overflow: hidden;

  .video-container {
    width: 100%;
    height: 100%;
    max-width: 720px;
    aspect-ratio: 16/9;
    object-fit: contain;
    display: block;
  }
}

.video-loading,
.video-error {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  font-size: 14px;
  gap: 8px;

  .el-icon {
    font-size: 24px;
    margin-bottom: 8px;
  }
}

.video-error {
  color: #ff7875;
}
</style>
